<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <BreadCard>{{this.$route.query.id ? '编辑文章':'发布文章'}}</BreadCard>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor v-model="form.content" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-radio-group v-model="form.cover" @change="hReSetImageList">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
         <el-form-item label="" v-if="form.cover>0">
          <el-row>
            <el-col :span="6" v-for="(item,idx) in form.cover" :key="idx">
                <Cover v-model="form.coverImages[idx]"/>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="频道" prop="channelId">
            <channel v-model="form.channelId"></channel>
        </el-form-item>
        <el-form-item v-show="!this.$route.query.id">
          <el-button type="primary" :loading="loading" @click="onSubmit(false)">发布</el-button>
          <el-button :loading="loading" @click="onSubmit(true)">存入草稿</el-button>
        </el-form-item>
        <el-form-item v-show="this.$route.query.id">
          <el-button type="primary" :loading="loading" @click="onSave()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入组件
import { quillEditor } from 'vue-quill-editor'
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'addArticle',
  components: {
    quillEditor
  },
  created () {
    this.getArtice()
  },
  watch: {
    '$route.query': function (newVal, oldVal) {
      console.log(this.$route.query)
      console.log(newVal, oldVal)
      if (Object.keys(newVal).length === 0) {
        console.log('用户把编辑改变为发布')
        this.loading = false
        this.form.title = ''
        this.form.content = ''
        this.form.cover = 0
        this.form.coverImages = []
        this.form.channelId = null
      }
    }
  },
  data () {
    return {
      loading: false,
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 粗体 斜体 下划线 中线
            ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
            [{ header: 1 }, { header: 2 }], // 标题 1级 2级 以后就没了需要配置源码
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            [{ indent: '-1' }, { indent: '+1' }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
            [{ font: [] }], // 字体种类-----[{ font: [] }]
            [{ align: [] }], // 对齐方式-----[{ align: [] }]
            ['image']
          ]
        }
      }, // 富文本配置项
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 5, max: 30, message: '标题5-30个字符串', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 20, message: '至少20个字符', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择文章频道', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '请选择封面', trigger: 'blur' }
        ]
      },
      form: {
        title: '', // 标题
        content: '', // 内容
        cover: 0, // 选项
        coverImages: [], // 保存对应的封面图的地址
        channelId: null // 接收的频道组件数据
      }
    }
  },
  methods: {
    hReSetImageList () {
      // 0,1,-1   =====> 3
      if (this.form.cover === 3) {
      } else if (this.form.cover === 1) {
        //  3 === > 1
        // this.form.coverImages.splice(1)
        this.form.coverImages = [this.form.coverImages[0]]
      }
    },
    onSubmit (draft) {
      // 用户点击了保存草稿
      // 1. 收集文章信息
      console.log(this.form)
      // 2. 验证数据- el-form表单
      this.$refs.form.validate(result => {
        console.log(result)
        // 验证通过
        if (result) {
          this.loading = true
          this.doAdd(draft)
        }
      })
    },
    async doAdd (draft) {
      try {
        const res = await this.$http({
          method: 'POST',
          url: `/mp/v1_0/articles?draft=${draft}`,
          // url: '/mp/v1_0/articles',
          data: {
          // draft,
            title: this.form.title,
            content: this.form.content,
            cover: {
              type: this.form.cover,
              images: this.form.coverImages
            },
            channel_id: this.form.channelId
          }
        })
        console.log(res)
        this.loading = false
        this.form.title = ''
        this.form.content = ''
        this.form.cover = 0
        this.form.coverImages = []
        this.form.channelId = null
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    getArtice () {
      if (this.$route.query.id) {
        this.getOneArtice()
      } else {
        console.log('当前是发布文章页面')
      }
    },
    async getOneArtice () {
      console.log('当前是编辑文章页面')
      // 判断id值是否存在
      const id = this.$route.query.id
      const res = await this.$http({
        method: 'GET',
        url: '/mp/v1_0/articles/' + id
      })
      console.log(res)
      // 判断对象是否为空对象
      // Object.keys(data).length === 0
      // JSON.stringify(data) == "{}"
      // for (var key in obj) {if ({}.hasOwnProperty.call(obj, key))return false;}return true;
      // Object.getOwnPropertyNames(data)===0
      if (JSON.stringify(res.data.data) === '{}') {
        this.$message.error('文章不存在,可以进行发布文章')
        this.$router.push({ path: '/addArticle' })
      } else {
        this.form.title = res.data.data.title
        this.form.content = res.data.data.content
        this.form.cover = res.data.data.cover.type
        this.form.coverImages = res.data.data.cover.images
        this.form.channelId = res.data.data.channel_id
      }
    },
    // 编辑文章
    onSave () {
      this.$refs.form.validate(result => {
        console.log(result)
        console.log(this.$route.query.id)
        // 验证通过
        try {
          const id = this.$route.query.id
          if (result) {
            this.loading = true
            this.$http({
              method: 'PUT',
              url: '/mp/v1_0/articles/' + id,
              data: {
              // draft,
                title: this.form.title,
                content: this.form.content,
                cover: {
                  type: this.form.cover,
                  images: this.form.coverImages
                },
                channel_id: this.form.channelId
              }
            })
            this.loading = false
            this.$router.push({ path: '/articles' })
            this.$message.success('修改成功')
          }
        } catch (err) {
          console.log(err)
          this.loading = false
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
// 在父组件中去设置子组件的样式，加上/deep/ 实现穿透功能
.publish-container /deep/ .ql-editor{
  height: 300px;
}
.publish-container /deep/ .ql-toolbar.ql-snow{
  padding: 0 8px;
}
</style>
